package org.intrasearch.core;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;

public class FileArtifactImpl extends ResourceArtifactBase<FileArtifact> implements FileArtifact, Externalizable
{
    private long fileSize;

    public FileArtifactImpl(String name, long fileSize, Set<String> urls)
    {
        super(urls, name);
        this.fileSize = fileSize;
    }

    @Override
    protected ArtifactId generateArtifactId()
    {
        return ArtifactId.generateFromBytes(digestBuffer(name, fileSize).array());
    }

    /**
     * Actually private. Used for serialization.
     */
    public FileArtifactImpl()
    {
    }

    private ByteBuffer digestBuffer(String fileName, long fileSize)
    {
        byte[] fileNameBytes = fileName.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(fileNameBytes.length + Long.SIZE / 8);
        buffer.put(fileNameBytes);
        buffer.putLong(fileSize);
        return buffer;
    }

    public long getFileSize()
    {
        return fileSize;
    }

    public FileArtifact merge(FileArtifact nextArtifact)
    {
        return new FileArtifactImpl(name, fileSize, mergeUrls(nextArtifact));
    }

    @Override
    public String toString()
    {
        return "FileArtifact: [" + name + "," + fileSize + "," + urls + "]";
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        super.writeExternal(out);
        out.writeLong(fileSize);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        super.readExternal(in);
        fileSize = in.readLong();
    }

}
